var gdbase = {
    debug:true    // 调试模式
};
// console.log = (function(oriLogFunc){
//     return function(str)
//     {
//         if(true === gdbase.debug){
//             oriLogFunc.call(console,str);
//         }
//     }
// })(console.log);
gdbase.api = {
    uploadUrl:'' // 上传地址
    ,uploadCheckFilemd5Url : '' //上传检测地址
};


$(function () {
    'use strict';

    $('a[data-toggle="ajaxModal"]').on('click',function () {
        var $this = $(this);
        var url = $this.attr('href');
        if(!url){
            layer.msg('url为空', {icon: 6,time:1000}, function (index) {

            });
            return false;
        }
        var tmp = url.split('?');
        var fenge = '?';
        if(tmp.length > 1){
            fenge = '&';
        }
        url += fenge + 't=' + (new Date()).getTime();
        var area = ['1000px'];
        if($this.data('width')){
            area[0] = $this.data('width');
        }
        if($this.data('height')){
            area[1] = $this.data('height');
        }
        var index = layer.open({
            type: 2,
            offset: '100px',
            title: $this.attr('title'),
            shadeClose: false,
            shade: 0.8,
            area: area,
            content: url //iframe的url
        });
        return false;
    })
})
$(function () {
    // ladda 按钮
    Ladda.bind( '.ladda-button', { timeout: 3000 } );
})
/* get执行并返回结果，执行后带跳转 */
$(function () {
    $('body').on('click','.confirm-rst-url-btn',function () {
        var $url = this.href,$info = $(this).data('info');
        layer.confirm($info, {icon: 3}, function (index) {
            layer.close(index);
            var lindex = layer.load(2, {time: 10*1000});
            $.post($url, function (data) {
                layer.close(lindex);
                if (data.code==1) {
                    layer.msg(data.msg, {icon: 6,time:1000}, function (index) {
                        layer.close(index);
                        window.location.href = data.url;
                    });
                } else {
                    layer.alert(data.msg, {icon: 5}, function (index) {
                        layer.close(index);
                    });
                }
            }, "json");
        });
        return false;
    });
});
/* 通用含验证码表单不带检查操作，失败不跳转 */
$(function () {
    $('.ajaxForm3').ajaxForm({
        success: complete3, // 这是提交后的方法
        dataType: 'json',
        beforeSubmit: function(arr, $form, options) {
            // form data array is an array of objects with name and value properties
            // [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
            // return false to cancel submit
            // 检测是否有图片框，然后进行提醒
            var image_select_hidden_kong = false;
            $($form).find('.image_select_hidden').each(function (i, row) {
                if(!$(this).val().length){
                    image_select_hidden_kong = true;
                }
            });
            var is_tijiao = true;
            if(image_select_hidden_kong){
                is_tijiao = confirm('图片未点击上传按钮，确认提交吗？');
            }
            if(!is_tijiao){
                Ladda.stopAll();
            }
            return is_tijiao;
        }
    });
});
//失败不跳转,验证码刷新
function complete3(data) {
    if (data.code == 1) {
        layer.msg(data.msg, {icon: 6}, function (index) {
            layer.close(index);
            window.location.href = data.url;
        });
    } else {
        layer.alert(data.msg, {icon: 5}, function (index) {
            $("#verify").val('');
            $("#verify_img").click();
            Ladda.stopAll();
            layer.close(index);
        });
    }
}

/**
 * 初始化上传组件
 * @param _el file 元素
 * @param _saveEl 保存的元素
 * @param _cbFilepreupload 上传前检测方法
 * @param _cbUploadSuccess 上传成功后的处理
 */
gdbase.initFileInput = function (_el,_saveEl,_cbFilepreupload,_cbUploadSuccess) {
    $(_el).LoadingOverlay("show");
    function init() {
        if(!_el || !_saveEl){
            alert('绑定元素不能为空，保存元素不能为空');
            return;
        }
        if(!$(_el).fileinput){
            alert('initFileInput 初始化失败');
            return;
        }
        var config = getInitialPreviewConfig(_saveEl);
        $(_el).fileinput({
            theme: 'explorer-fa',
            language: 'zh',
            uploadUrl: gdbase.api.uploadUrl,
            uploadExtraData: {
                'source': 'file-input'
            },
            showCaption:false,
            dropZoneEnabled:false,
            multiple: true,
            showUpload: true,
            showRemove: true,
            showDrag: true,
            initialPreviewAsData: false,
            initialPreview: getInitialPreview(_saveEl),
            initialPreviewConfig: config
        }).on('fileerror', function(event, data, msg) {
            console.log(data);
            // get message
            alert(msg);
        }).on('fileloaded', function(event, file, previewId, index, reader) {
            // 文件加载后，提交到服务器做 md5 识别
            checkFile(_el,index,file);
            console.log("fileloaded");
        }).on('filepreupload', function(event, data, previewId, index) {
            // 上传前检测
            if('function' == typeof _cbFilepreupload){
                _cbFilepreupload(data,previewId,index);
            }
            console.log('File pre upload triggered');
        }).on('fileuploaded', function (event, data, previewId, index) {
            // 上传成功
            console.log("fileuploaded");
            if('function' == typeof _cbUploadSuccess){
                _cbUploadSuccess(data['response'],previewId,index);
            }
            else{
                if(data['response']['code']){
                    $(_saveEl).val(data['response']['data']['url']);
                }
            }
        });

        console.log('图片框加载完成');

        $(_el).LoadingOverlay("hide");

        function getInitialPreview(_ell) {
            var html = [];
            $(_ell).each(function (i, row) {
                if($(row).val()){
                    html.push('<div class="file-preview-image"><img src="'+$(row).val()+'" class="file-preview-image kv-preview-data" style="width:auto;height:60px;max-width:100%;max-height:100%;"></div>');
                }
            });
            return html;
        }
        function getInitialPreviewConfig(_ell) {
            var config = [];
            $(_ell).each(function (i, row) {
                var tmpVal = $(row).val();
                if(tmpVal){
                    config.push({
                        caption: $(row).attr('text'),
                        key: tmpVal,
                        url: gdbase.api.uploadUrl + '?source=file_delete_empty'
                    });
                }
            });
            return config;
        }

        /**
         * 检测文件md5
         */
        function checkFile(_el, _index,_file) {
            var fileReader = new FileReader();
            var blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice;
            var chunkSize = 2097152,
                // read in chunks of 2MB
                chunks = Math.ceil(_file.size / chunkSize), currentChunk = 0;
            var spark = new SparkMD5();
            fileReader.onload = function(e) {
                console.log("read chunk nr", currentChunk + 1, "of", chunks);
                spark.appendBinary(e.target.result);
                // append binary string
                currentChunk++;

                if (currentChunk < chunks) {
                    loadNext();
                } else {
                    console.log("finished loading");
                    var md5 = spark.end();
                    console.log("computed hash", md5);
                    // compute hash
                    // 获取完成 提交检测
                    getCheckData(_el,_index,md5)
                }
            };

            function loadNext() {
                var start = currentChunk * chunkSize, end = start + chunkSize >= _file.size ? _file.size : start + chunkSize;
                fileReader.readAsBinaryString(blobSlice.call(_file, start, end));
            }
            loadNext();
        }

        function getCheckData(_el,_index,_md5) {
            console.log('getCheckData');
            $.getJSON(gdbase.api.uploadCheckFilemd5Url,{hash:_md5},function (json) {
                // console.log(json);
                // 存在文件，跳过
                if(json['code']){
                    console.log('文件存在');
                    setFileSuccess(_el,_index);
                    if('function' == typeof _cbUploadSuccess){
                        _cbUploadSuccess(json,0,_index);
                    }
                    else{
                        if(json['data']){
                            $(_saveEl).val(json['data']['url']);
                        }
                    }
                }
            })
        }

        /**
         * 设置文件成功
         * @param _el
         * @param _index
         */
        function setFileSuccess(_el, _index) {
            $frames = $(_el).fileinput('getFrames');
            $frames.find('.file-thumb-progress').eq(_index).removeClass('kv-hidden').find('.progress-bar').removeClass([
                'progress-bar-striped','active'
            ]).attr('aria-valuenow',100).css('width','100%').html('完成，秒传');
            $frames.find('.file-upload-indicator').eq(_index).prop('title','上传').html('<i class="fa fa-check-circle text-success"></i>');
            $frames.find('.file-footer-buttons').eq(_index).find('.kv-file-upload').hide(0);
            $(_el).fileinput('updateStack', _index, null);
        }
    }
    head.load([
        '/static/bootstrap-fileinput/css/fileinput.min.css' + '?' + gdbase.site.version
        ,'/static/bootstrap-fileinput/js/fileinput.min.js' + '?' + gdbase.site.version
        ,'https://cdn.bootcss.com/spark-md5/3.0.0/spark-md5.min.js' + '?' + gdbase.site.version
    ],function () {
        setTimeout(init,500);
    });
}
/**
 * 初始化 um 编辑器
 * @param _el
 */
gdbase.initUmEditor = function(_el) {
    $(_el).LoadingOverlay("show");
    head.load([
        gdbase.site.static_path + '/umeditor/1.2.3/themes/default/css/umeditor.min.css' + '?' + gdbase.site.version
        ,gdbase.site.static_path + '/umeditor/1.2.3/umeditor.min.js' + '?' + gdbase.site.version
        ,gdbase.site.static_path + '/umeditor/template.min.js' + '?' + gdbase.site.version
        ,'https://cdn.bootcss.com/spark-md5/3.0.0/spark-md5.min.js' + '?' + gdbase.site.version
    ],function () {
        var element = $(_el);
        etpl.config({
            commandOpen: '<%',
            commandClose: '%>'
        });
        $.getJSON(gdbase.api.umEditorConfigUrl,{},function (json) {
            json['UMEDITOR_HOME_URL'] = window.UMEDITOR_HOME_URL;
            window.UMEDITOR_CONFIG = json;

            setTimeout(function () {
                var id = element.attr('id');
                var um = UM.getEditor(id, {
                    imageUrl: gdbase.api.uploadUrl + '?source=um-editor',
                    uploadCheckFilemd5Url: gdbase.api.uploadCheckFilemd5Url,
                    imagePath: '',
                    initialFrameHeight: 400
                });
                um.addListener('contentchange', function () {
                    element.val(um.getContent());
                });
                um.addListener('ready',function () {
                    $(_el).LoadingOverlay("hide");
                    console.log('编辑框加载完成');
                })
            },100);
        })
    });
};
/**
 * 单选，多选  图片
 * @param op
 */
gdbase.uploadMultiImages = function(op){
    var canshu = {
        inputName:''
        ,elm:''
        ,multi:0
    };
    var init = function() {
        canshu.inputName = op.inputName;
        canshu.elm = op.elm;
        canshu.multi = op.multi;

        $(canshu.elm).on('click','.btn-select',function () {
            openWin();
        })

        $('.multi-img-box-' + canshu.inputName).find('.multi-img-details').on('click','em.close',function () {
            $(this).parent().remove();
            setHideValue(canshu.inputName);
        })

        // 初始化已经存在的值
        var zhi = getHideValue();
        if (zhi) {
            var zhis = zhi.split(',');
            render(canshu.inputName,zhis);
        }
    }

    var openWin = function() {
        var url = gdbase.api.selectPhotoUrl + "?cb=gdbase.uploadMultiImagesCallBack&fieldname=" + canshu.inputName;
        layer.open({
            type: 2,
            title: '选择图片',
            shadeClose: false,
            shade: 0.5,
            area: ['1000px', '650px'],
            content: url //iframe的url
        });
    }

    function setHideValue(_fieldName) {
        var _urls = [];
        $(".h-img-" + _fieldName).each(function () {
            _urls.push($(this).val())
        })
        $('#h_' + _fieldName).val(_urls.join(','));
    }
    function getHideValue() {
        return $('#h_' + canshu.inputName).val();
    }

    function render(_fieldName,_data) {
        var htmls = [];
        $.each(_data, function(idx, url){
            if(!url){
                return true;
            }
            htmls.push('<div class="multi-item">' +
                '<img onerror="this.src=\'/static/admin/img/nopic.png\'; this.title=\'图片未找到.\'" src="'+url+'" class="img-responsive img-thumbnail">' +
                '<input type="hidden" class="h-img-'+_fieldName+'" value="'+url+'">'+
                '<em class="close" title="删除这张图片">×</em>' +
                '</div>');
            if(!canshu.multi){
                return false;
            }
        });
        var html = htmls.join('');
        if(canshu.multi){
            $('.multi-img-box-' + _fieldName).find('.multi-img-details').append(html);
        }
        else{
            $('.multi-img-box-' + _fieldName).find('.multi-img-details').html(html);
        }
    }

    /**
     * 回调
     * @param _fieldName
     * @param _data
     */
    this.uploadMultiImagesCallBack = function(_fieldName,_data){
        render(_fieldName,_data);

        setHideValue(_fieldName);
    }

    init();
};

/**
 * 头像错误，使用默认头像
 */
function memberAvatarOnerror(_obj) {
    _obj.src = '/static/admin/img/noface.png';
}

/**
 * 商品图片，不存在使用默认
 * @param _obj
 */
function goodsAvatarOnerror(_obj) {
    _obj.src = '/static/admin/img/nopic.png';
}